var listVue = new Vue({
	el: "body",
	data: {
		productType: [],
		isLoading: true
	},
	created: function() {
		init();
		_this = this;
		selectType(_this)
	},
	methods: {
		myType: function() {
			location.href = "./type.html"
		},
		myCart: function() {
			location.href = "./cart.html"
		},
		cart: function(a) {
			event.stopPropagation();
			indexAddCart(a)
		},
		detail: function(id) {
			location.href = "detail.html?id=" + id
		}
	}
})

function selectType(a) {
	var type = getUrlPro("type")
	var query = new AV.Query('Product');
	query.equalTo("type", type);
	query.find().then(function(products) {
		a.productType = products;
		a.isLoading = false
	}).catch(function(error) {
		console.log(JSON.stringify(error));
	});
}

function indexAddCart(t) {
	currentUser = AV.User.current();
	if(currentUser) {
		var pid = _this.productType[t].attributes.pid //商品id
		console.log(pid)
		var user = currentUser.attributes.username //当前登录用户
		var id = new AV.Query('Cart');
		id.equalTo("pid", pid);
		var username = new AV.Query('Cart');
		username.equalTo("username", user);
		//设置组合查询的条件
		var cart = AV.Query.and(id, username);
		cart.find().then(function(products) {
			if(products.length == 0) {
				addCart(user, pid)
			} else {
				var query = new AV.Query('Cart');
				query.equalTo("pid", pid);
				query.find().then(function(products) {
					console.log(products)
					var num = products[0].attributes.num //当前购物车里该商品的数量  
					var rid = products[0].id //该商品在购物车里的真实id
					console.log(rid)
					console.log(num)
					//购物车里已经添加过当前商品，只是修改数量
					var todo = AV.Object.createWithoutData('Cart', rid);
					todo.set('num', ++num);
					// 保存到云端
					todo.save();
					$.toast("加入成功", function() {
						console.log('close');
					});
				}).catch(function(error) {
					console.log(JSON.stringify(error));
				});
			}
		}).catch(function(error) {
			console.log(JSON.stringify(error));
		});
	} else {
		location.href = "login.html?RetUrl=" + getPageUrl2()
	}
}

function addCart(a, b) {
	var Product = AV.Object.extend('Cart')
	var product = new Product();
	product.set('username', a);
	product.set('pid', b);
	product.set('num', 1);
	product.save().then(function() {
		$.toast("加入成功", function() {
			console.log('close');
		});
	}, function(error) {
		alert("failure")
	});
}